/*
 * UserNet  --  TCP/IP implementation in userspace
 * Copyright (C) 2010  Robert Millan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <errno.h>
#include <error.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/param.h>		/* MIN */

#include "unet/misc.h"
#include "unet/rpc.h"
#include "unet/ipc.h"
#include "unet/ip.h"

/* Remote Procedure Call (RPC) services provided by the UserNet server.  */

static int server_fd = -1;
static pthread_mutex_t server_fd_mutex = PTHREAD_MUTEX_INITIALIZER;

static int
prepare_req (int fd, struct unet_rpc_req *req)
{
  struct unet_rpc_adv adv;
  if (read (fd, &adv, sizeof (adv)) != sizeof (adv))
    return -1;

  if (adv.signature != UNET_SIGNATURE)
    {
      errno = ENOSYS;
      error (0, 0, "Server sent invalid signature");
      return -1;
    }

  if (adv.server_abi.min > UNET_MAX_CLIENT_ABI)
    {
      errno = ENOSYS;
      error (0, 0, "Server ABI is too new");
      return -1;
    }

#if UNET_MIN_CLIENT_ABI > 0
  if (adv.server_abi.max < UNET_MIN_CLIENT_ABI)
    {
      error (0, 0, "Server ABI is too old, this client no longer supports it");
      errno = ENOSYS;
      return -1;
    }
#endif

  memset (req, 0, sizeof (*req));
  req->signature = UNET_SIGNATURE;
#if UNET_MAX_CLIENT_ABI > 0
  req->abi = MIN (adv.server_abi.max, UNET_MAX_CLIENT_ABI);
#else
  req->abi = adv.server_abi.max;
#endif

  return 0;
}

static inline int
send_req (int fd, struct unet_rpc_req *req, void *ack, size_t ack_len)
{
  debug_printf ("rpc", "sending request to server (type = %u) ... ", req->type);

  if (write (fd, req, sizeof (*req)) != sizeof (*req))
    return -1;

  if (read (fd, ack, ack_len) != ack_len)
    return -1;

  debug_printf ("rpc", "received ack from server\n");

  return 0;
}

static void *
incoming_packet_dispatcher (void *arg)
{
  uint8_t packet[IP_MAXPACKET];

  while (1)
    {
      size_t len;
      len = read (server_fd, packet, sizeof (packet));

      if (len == -1)
	error (1, errno, "read");

      if (len == 0)
	error (1, 0, "IPC channel was closed by server");

      debug_printf ("rpc", "got %zu-byte packet from server\n", len);

      unet_ip_incoming_packet (packet, len);
    }

  return NULL;
}

int
unet_rpc_init ()
{
  struct unet_rpc_req req;
  struct unet_rpc_ack ack;

  debug_printf ("rpc", "unet_rpc_init()\n");

  pthread_mutex_lock (& server_fd_mutex);

  if (server_fd != -1)
    {
      errno = EALREADY;
      goto fail;
    }

  int fd = unet_ipc_connect ();
  if (fd == -1)
    goto fail;

  if (prepare_req (fd, &req) == -1)
    goto fail_close;

  req.type = UNET_RPC_INIT;

  if (send_req (fd, &req, &ack, sizeof (ack)) == -1)
    goto fail_close;

  if (ack.status != 0)
  {
    errno = ack.status;
    goto fail_close;
  }

  server_fd = fd;

  pthread_t thread;
  pthread_create (&thread,
		  NULL /* default attributes */,
		  incoming_packet_dispatcher, NULL);
  return 0;

 fail_close:
  close (fd);

 fail:
  pthread_mutex_unlock (& server_fd_mutex);

  return errno ? -1 : 0;
}

void
unet_rpc_fini ()
{
  close (server_fd);
  server_fd = -1;
  pthread_mutex_unlock (& server_fd_mutex);

  debug_printf ("rpc", "unet_rpc_fini()\n");
}

/* Notify the server that an outgoing packet has to be sent.  */
int
unet_rpc_ip_send_packet (const uint8_t *packet, const uint32_t len)
{
  if (server_fd == -1)
    {
      errno = ENETDOWN;
      return -1;
    }

  return write (server_fd, packet, len);
}

int
unet_rpc_port (uint8_t type, uint8_t op, struct in_addr listen_addr, uint16_t *num)
{
  int fd;
  struct unet_rpc_req req;
  struct unet_rpc_port_ack ack;

  errno = 0;

  if (server_fd == -1)
    {
      errno = ENETDOWN;
      return -1;
    }

  fd = unet_ipc_connect ();
  if (fd == -1)
    goto fail;

  if (prepare_req (fd, &req) == -1)
    goto fail_close;

  req.type = UNET_RPC_PORT;
  req.data.port.op = op;
  req.data.port.type = type;
  req.data.port.num = *num;
  req.data.port.listen_addr = listen_addr;

  if (send_req (fd, &req, &ack, sizeof (ack)) == -1)
    goto fail_close;

  *num = ack.num;
  errno = ack.status;

 fail_close:
  close (fd);

 fail:
  return errno ? -1 : 0;
}

int
unet_rpc_get_device_info (unsigned int id, struct unet_device *device)
{
  int fd;
  struct unet_rpc_req req;
  struct unet_rpc_get_device_info_ack ack;

  errno = 0;

  fd = unet_ipc_connect ();
  if (fd == -1)
    goto fail;

  if (prepare_req (fd, &req) == -1)
    goto fail_close;

  req.type = UNET_RPC_GET_DEVICE_INFO;
  req.data.get_device_info.id = id;

  if (send_req (fd, &req, &ack, sizeof (ack)) == -1)
    goto fail_close;

  errno = ack.status;

  if (ack.status == 0)
    memcpy (device, &ack.device, sizeof (*device));

 fail_close:
  close (fd);

 fail:
  return errno ? -1 : 0;
}

int
unet_rpc_set_device_info (const struct unet_device *device)
{
  int fd;
  struct unet_rpc_req req;
  struct unet_rpc_ack ack;

  errno = 0;

  fd = unet_ipc_connect ();
  if (fd == -1)
    goto fail;

  if (prepare_req (fd, &req) == -1)
    goto fail_close;

  req.type = UNET_RPC_SET_DEVICE_INFO;
  req.data.set_device_info.device = *device;

  if (send_req (fd, &req, &ack, sizeof (ack)) == -1)
    goto fail_close;

  errno = ack.status;

 fail_close:
  close (fd);

 fail:
  return errno ? -1 : 0;
}

int
unet_rpc_count_devices ()
{
  int fd;
  struct unet_rpc_count_ack ack;
  struct unet_rpc_req req;

  errno = 0;

  fd = unet_ipc_connect ();
  if (fd == -1)
    goto fail;

  if (prepare_req (fd, &req) == -1)
    goto fail_close;

  req.type = UNET_RPC_COUNT_DEVICES;

  if (send_req (fd, &req, &ack, sizeof (ack)) == -1)
    goto fail_close;

  errno = ack.status;

 fail_close:
  close (fd);

 fail:
  return errno ? -1 : ack.count;
}

int
unet_rpc_route_add (const struct unet_route *route)
{
  int fd;
  struct unet_rpc_ack ack;
  struct unet_rpc_req req;

  errno = 0;

  fd = unet_ipc_connect ();
  if (fd == -1)
    goto fail;

  if (prepare_req (fd, &req) == -1)
    goto fail_close;

  req.type = UNET_RPC_ROUTE_ADD;
  req.data.route = *route;

  if (send_req (fd, &req, &ack, sizeof (ack)) == -1)
    goto fail_close;

  errno = ack.status;

 fail_close:
  close (fd);

 fail:
  return errno ? -1 : 0;
}

int
unet_rpc_route_del (const struct unet_route *route)
{
  int fd;
  struct unet_rpc_ack ack;
  struct unet_rpc_req req;

  errno = 0;

  fd = unet_ipc_connect ();
  if (fd == -1)
    goto fail;

  if (prepare_req (fd, &req) == -1)
    goto fail_close;

  req.type = UNET_RPC_ROUTE_DEL;
  req.data.route = *route;

  if (send_req (fd, &req, &ack, sizeof (ack)) == -1)
    goto fail_close;

  errno = ack.status;

 fail_close:
  close (fd);

 fail:
  return errno ? -1 : 0;
}

int
unet_rpc_route_count ()
{
  int fd;
  struct unet_rpc_count_ack ack;
  struct unet_rpc_req req;

  errno = 0;

  fd = unet_ipc_connect ();
  if (fd == -1)
    goto fail;

  if (prepare_req (fd, &req) == -1)
    goto fail_close;

  req.type = UNET_RPC_ROUTE_COUNT;

  if (send_req (fd, &req, &ack, sizeof (ack)) == -1)
    goto fail_close;

  errno = ack.status;

 fail_close:
  close (fd);

 fail:
  return errno ? -1 : ack.count;
}

int
unet_rpc_route_get (const uint32_t id, struct unet_route *route)
{
  int fd;
  struct unet_rpc_req req;
  struct unet_rpc_route_get_ack ack;

  errno = 0;

  fd = unet_ipc_connect ();
  if (fd == -1)
    goto fail;

  if (prepare_req (fd, &req) == -1)
    goto fail_close;

  req.type = UNET_RPC_ROUTE_GET;
  req.data.route_get = id;

  if (send_req (fd, &req, &ack, sizeof (ack)) == -1)
    goto fail_close;

  errno = ack.status;

  if (ack.status == 0)
    memcpy (route, &ack.route, sizeof (*route));

 fail_close:
  close (fd);

 fail:
  return errno ? -1 : 0;
}
